package org.benxiong.iplay.ui;

import org.benxiong.iplay.R;
import org.benxiong.iplay.http.request.RequestFactory;
import org.benxiong.iplay.util.Constants;
import org.benxiong.iplay.util.GlobalVar;
import org.benxiong.iplay.util.LogX;
import org.benxiong.iplay.util.PreferencesUtil;
import org.benxiong.iplay.util.ServerUtilities;
import org.benxiong.iplay.util.ToastUtil;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;

import com.google.android.gcm.GCMRegistrar;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

/**
 * Activity which displays a login screen to the user, offering registration as
 * well.
 */
public class LoginActivity extends BaseActivity {
	/**
	 * A dummy authentication store containing known user names and passwords.
	 * TODO: remove after connecting to a real authentication system.
	 */
	private static final String[]	DUMMY_CREDENTIALS	= new String[] {
														"foo@example.com:hello", "bar@example.com:world" };

	/**
	 * The default email to populate the email field with.
	 */
	public static final String		EXTRA_EMAIL			= "com.example.android.authenticatordemo.extra.EMAIL";

	// Values for email and password at the time of the login attempt.
	private String					mUsername;
	private String					mPassword;

	// UI references.
	private EditText				mEmailView;
	private EditText				mPasswordView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_login);

		// Set up the login form.
		mUsername = getIntent().getStringExtra(EXTRA_EMAIL);
		mEmailView = (EditText) findViewById(R.id.email);
		mEmailView.setText(mUsername);

		mPasswordView = (EditText) findViewById(R.id.password);
		mPasswordView
				.setOnEditorActionListener(new TextView.OnEditorActionListener() {
					@Override
					public boolean onEditorAction(TextView textView, int id,
							KeyEvent keyEvent) {
						if (id == R.id.login || id == EditorInfo.IME_NULL) {
							attemptLogin();
							return true;
						}
						return false;
					}
				});

		findViewById(R.id.login).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						attemptLogin();
					}
				});

		findViewById(R.id.join).setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				jumpToActivity(RegisterActivity.class);
			}
		});

		getActionBar().setHomeButtonEnabled(false);
	}

	/**
	 * Attempts to sign in or register the account specified by the login form.
	 * If there are form errors (invalid email, missing fields, etc.), the
	 * errors are presented and no actual login attempt is made.
	 */
	public void attemptLogin() {
		// Reset errors.
		mEmailView.setError(null);
		mPasswordView.setError(null);

		// Store values at the time of the login attempt.
		mUsername = mEmailView.getText().toString();
		mPassword = mPasswordView.getText().toString();

		boolean cancel = false;
		View focusView = null;

		// Check for a valid password.
		if (TextUtils.isEmpty(mPassword)) {
			mPasswordView.setError(getString(R.string.error_field_required));
			focusView = mPasswordView;
			cancel = true;
		} else if (mPassword.length() < 4) {
			mPasswordView.setError(getString(R.string.error_invalid_password));
			focusView = mPasswordView;
			cancel = true;
		}

		// Check for a valid email address.
		if (TextUtils.isEmpty(mUsername)) {
			mEmailView.setError(getString(R.string.error_field_required));
			focusView = mEmailView;
			cancel = true;
		}

		if (cancel) {
			// There was an error; don't attempt login and focus the first
			// form field with an error.
			focusView.requestFocus();
		} else {
			// Show a progress spinner, and kick off a background task to
			// perform the user login attempt.
			showLoading(R.string.login_progress_signing_in);
			// mAuthTask = new UserLoginTask();
			// mAuthTask.execute((Void) null);

			RequestParams rParam = new RequestParams();
			rParam.put("username", mUsername);
			rParam.put("password", mPassword);
			rParam.put("tokenId", GlobalVar.tokenId);

			RequestFactory.getInstance().post(RequestFactory.URL_LOGIN, rParam, new AsyncHttpResponseHandler() {
				@Override
				public void onSuccess(String response) {
					LogX.print(response);
					mProgressDialog.dismiss();
					try {
						JSONObject json = new JSONObject(response);
						String code = json.getString("code");
						if (shouldProcess(response)) {
							// register success
							finish();
							PreferencesUtil.saveLoginInfo(mUsername, mPassword);
							jumpToActivity(MemberActivity.class);
						} 
					} catch (JSONException e) {
						e.printStackTrace();
					}

				}

				@Override
				public void onFailure(Throwable arg0) {
					// TODO Auto-generated method stub
					super.onFailure(arg0);
					hideLoading();
					LogX.print("onFailure: " + arg0.getMessage());
				}

			});
		}
	}

	@Override
	protected void initView() {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		return true;
	}

	@Override
	public void onMessage(Message msg) {

	}

	@Override
	public void handleClick(int buttonId) {

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (resultCode == 1) {
			// register success , login automatically
			finish();
			jumpToActivity(HomeActivity.class);
		}
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		// GCM message registration
		GCMRegistrar.checkDevice(this);
		GCMRegistrar.checkManifest(this);

		new AsyncTask() {

			@Override
			protected Object doInBackground(Object... params) {
				final String regId = GCMRegistrar.getRegistrationId(LoginActivity.this);
				if (regId.equals("")) {
					GCMRegistrar.register(LoginActivity.this, Constants.GCM_SENDER_ID);
				} else {
					GlobalVar.tokenId = regId;
					if (!PreferencesUtil.isGCMRegSuccess()) {
						ServerUtilities.register(LoginActivity.this, regId);
					}
				}
				return null;
			}

		}.execute();
	}
}
